/**
 * Created by Xiaoming on 2017/9/28.
 */
angular.module('module.scan')
    .controller('ScanController', ScanController);
// 用户优惠券列表
ScanController.$inject = ['$scope',  '$stateParams', '$state', '$cookies', 'WxjssdkService', 'GoodsService', 'ShopMenuService', 'OrderService', '$interval', 'CupboarlockService','MsgmqhpService','IMSdkService'];
function ScanController($scope, $stateParams, $state, $cookies, WxjssdkService, GoodsService, ShopMenuService, OrderService, $interval, CupboarlockService,MsgmqhpService,IMSdkService) {
    var vm = this;
    vm.shopid = $stateParams.shopid;
    vm.goodslist = [];
    vm.textpromt = "关门自动结算";
    vm.entrance_shop = entrance_shop;
    vm.add = add;
    vm.remove = remove;
    var scanStatus = false;//扫码状态，默认进来没有触发
    var device = {
        devid:'50051',
        num:1
    };
    if($stateParams.devid){
        device = $stateParams.devid;
    }
    vm.init_scan_icon = init_scan_icon;//悬浮扫码拖动效果
    var appid = $stateParams.lock_appid;//获取appid
    vm.goodscontent = ShopMenuService.gettotalpriceandcount(vm.shopid);
    vm.notrash = notrash;
    $scope.$watch("vm.lockStatus",function () {
        if (vm.lockStatus == 1) {
            //按钮处于判断状态
            $("#scan_button").attr("disabled","true");
        }
        else if (vm.lockStatus == 2 || vm.lockStatus == 3) {
            $("#scan_button").removeAttr("disabled");
            if(vm.lockStatus == 3){
                vm.sure_click(1);
            }
        }
    });
    /* GoodsService.getByBarcode(476429753,6907992103648).$promise.then(function (goods) {
     ShopMenuService.addBarcode(vm.shopid,goods);
     vm.goodslist = ShopMenuService.getShopCarByShopid(vm.shopid);
     vm.goodscontent = ShopMenuServicgettotalpriceandcount(vm.shopid);
     },function(){
     alert("获取商品信息失败")
     });*/
    ///////////////////////////////////////////////////
    /*function auto_account() {
        _time = $interval(function () {
            CupboarlockService.getstatus(device).$promise.then(function (data) {
                if (data.lock == 2) {
                    //说明门是关着
                    vm.sure_click(1);
                    $interval.cancel(_time);
                }
            })
        }, 3000);//定时查询锁状态，每隔3秒查询一次检测到门关着调起支付
        $scope.$on('$destroy', function () {
            $interval.cancel(_time);
        });//离开控制器取消定时器
    }*/

    //var appid = mall_userauth.wxmp_appid;
    /*GoodsService.getByBarcode(vm.shopid,6970066550846).$promise.then(function (goods) {
     ShopMenuService.addBarcode(vm.shopid,goods);
     vm.goodslist = ShopMenuService.getShopCarByShopid(vm.shopid);
     vm.goodscontent = ShopMenuService.gettotalpriceandcount(vm.shopid);
     },function(){
     alert("获取商品信息失败")
     });*/
    function wxjsdkConfig() {
        var environment = environment_judge();
        var url = "", trueurl;
        if (environment.isIOS && environment.isWx) {
            trueurl = WxjssdkService.getSpaUrl();
        } else {
            url = window.location.href;
            trueurl = url;
            if (url.indexOf("#") > 0) {
                trueurl = url.substring(0, url.indexOf("#"));
            }
        }
        //alert("trueurl"+trueurl);
        var postinfo = {
            "component_appid": mall_userauth.component_appid,
            "mer_id": appid,
            "path": trueurl
        };
        WxjssdkService.get_ticket(postinfo).$promise.then(function (wxconfig) {
            //alert("微信配置："+JSON.stringify(wxconfig));
            ///*调起扫描二维码*/
            wx.config({
                debug: false,
                appId: appid,
                timestamp: wxconfig.timestamp,
                nonceStr: wxconfig.nonceStr,
                signature: wxconfig.signature,
                jsApiList: ['checkJsApi', 'scanQRCode']
            });//end_config
            wx.error(function (res) {
                //wxjsdkConfig();
                // alert("出错了：" + JSON.stringify(res));
            });
            wx.ready(function () {
                wx.checkJsApi({
                    jsApiList: ['scanQRCode'],
                    success: function (res) {
                    }
                });
                //扫描二维码
                vm.scanQRCode = function (status) {
                    wx.scanQRCode({
                        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                        success: function (res) {
                            var result = res.resultStr;// 当needResult 为 1 时，扫码返回的结果
                            var barcode = result.split(',')[1];
                            //alert("获取扫码信息"+JSON.stringify(result));
                            $scope.$apply(function () {
                                GoodsService.getByBarcode(vm.shopid, barcode).$promise.then(function (goods) {
                                    scanStatus = true;//用户扫过码
                                    vm.scanConfim ={
                                        scanAgain:'还有没扫的',
                                        chooseOk:'我已经选好了',
                                    };
                                    ShopMenuService.addBarcode(vm.shopid, goods);
                                    vm.goodslist = ShopMenuService.getShopCarByShopid(vm.shopid);
                                    vm.goodscontent = ShopMenuService.gettotalpriceandcount(vm.shopid);
                                }, function () {
                                    alert("获取商品信息失败")
                                });
                            });
                        }
                    });
                };
            });//end_ready
            ///*微信扫一扫结束*/
        });
    }
    wxjsdkConfig();
    //},500);
    function entrance_shop() {
        $state.go("store", {shopid: 977534855, appid: "wxd58951ae0414cb55",});
    }

    //添加商品减少商品
    function add(goods) {
        ShopMenuService.addBarcode(vm.shopid, goods);
        vm.goodslist = ShopMenuService.getShopCarByShopid(vm.shopid);
        vm.goodscontent = ShopMenuService.gettotalpriceandcount(vm.shopid);
    }

    function remove(goods) {
        if (goods.num == 1) {
            $(".contain-item").fadeIn();
            vm.trash = trash;
            function trash() {//清空
                ShopMenuService.removeBarcode(vm.shopid, goods);
                vm.shopbuygoods = ShopMenuService.getShopCarByShopid(vm.shopid);
                vm.goodscontent = ShopMenuService.gettotalpriceandcount(vm.shopid);
                $(".contain-item").fadeOut();
            }
        } else {
            ShopMenuService.removeBarcode(vm.shopid, goods);
            vm.goodslist = ShopMenuService.getShopCarByShopid(vm.shopid);
            vm.goodscontent = ShopMenuService.gettotalpriceandcount(vm.shopid);
        }
    }

    //下单按钮
    vm.user = {};
    vm.sure_click = function (type) {
        //没东西的场景
        if (ShopMenuService.buyNowShopById(vm.shopid) == null) {
            if(!scanStatus){
                vm.scanConfim ={
                    scanAgain:'还有没扫的',
                    chooseOk:'谢谢使用'
                };
                ConfirmbBox();
            }else{
                vm.scanConfim ={
                    scanAgain:'还有没扫的',
                    chooseOk:'已经选好了'
                };
                ConfirmbBox();
            }
            return;
        }
        //有商品且商品为0
        vm.order = ShopMenuService.buyNowShopById(vm.shopid)[0];
        if (!$cookies.get("_userId")) {
            input_alert("请先登录");
        } else {
            if (type == 1) {
                //代表用户第一次进入结算页面，提示用户是否有未结算商品
                vm.scanConfim ={
                    scanAgain:'还有没扫的',
                    chooseOk:'已经选好了'
                };
                confirm_box($("#comfirmbox"), "show", function () {
                    confirm_box($("#comfirmbox"), "hide");
                    vm.textpromt = "去结算";
                    vm.scanQRCode();
                }, function () {
                    account_pay();
                });
            } else {
                //否则用户是通过下次点击进入结算，直接结算商品
                account_pay();
            }

        }
    };
    //支付跳转
    function account_pay() {
        if (vm.goodscontent.totalprice == 0 || vm.goodscontent.totalprice == undefined) {
            alert('订单金额为0');
        } else {
            var order = {
                creatorid: $cookies.get("_userId"),//测试环境
                buyMessage: vm.buyMessage,
                type: 6,
                receiverName: vm.user.nickname,
                receiverPhone: vm.user.phone,
                accesscode: {
                    accesscode: "",
                    appid: appid,
                    openid: "",
                },
                ordersShops: []
            };
            var goods_list = vm.order.list;
            var OrdersShopsReq = {
                shopid: vm.shopid,
                ordersShopsGoods: [],
                ordersShopsPrivileges: []
            };
            for (var j = 0; j < goods_list.length; j++) {
                var goods = goods_list[j];
                OrdersShopsReq.ordersShopsGoods.push({
                    shopid: $stateParams.shopid,
                    goodsid: goods.goodsid,
                    skuid: goods.skuid,
                    fee: goods.price,
                    currentFee: goods.currentFee,
                    num: goods.num
                });
            }
            console.log(OrdersShopsReq);
            order.ordersShops.push(OrdersShopsReq);
            //return;
            OrderService.createOrder(order).$promise.then(function (newOrder) {
                if (newOrder.sumPrice < 0.001) {
                    input_alert("订单创建失败", 1000);
                    setTimeout(function () {
                    }, 1000);
                } else {
                    window.location.href = jumpurl(newOrder.orderid, "", "", encodeURI(vm.order.shop.name), $cookies.get("_userId"), vm.goodscontent.totalprice, encodeURI("扫码订单"), appid, vm.shopid);
                }
            }, function (error) {
                if (error.data) {
                    input_alert(error.data.reason, 2000);
                } else {
                    input_alert("创建订单失败", 2000);
                }
                setTimeout(function () {
                }, 1000);
            });
        }
    }

    function touchStart() {
        $("#scan_icon_button").animate({
            opacity: 1,
        }, 200)
    }

    function touchMove() {
        event.preventDefault();
        var touch = event.touches[0];
        $("#scan_icon_button").css("top", touch.clientY - 27.5 + 'px');
        $("#scan_icon_button").css("left", touch.clientX - 27.5 + 'px');
    }

    function touchEnd() {
        var touch = event.changedTouches[0];
        var scanIconButton = $("#scan_icon_button");
        if (touch.clientY < 55) {
            scanIconButton.animate({
                top: 0,
            }, 100)
        }
        else if (touch.clientY > window.innerHeight - 55) {
            scanIconButton.animate({
                top: window.innerHeight - 55,
            }, 100)
        }
        else if (touch.clientX < 55) {
            scanIconButton.animate({
                left: 0,
            }, 100)
        } else if (touch.clientX > window.innerWidth - 55) {
            scanIconButton.animate({
                left: window.innerWidth - 55,
            }, 100)
        }
        scanIconButton.animate({
            opacity: 0.6,
        }, 800)
    }

    function init_scan_icon() {
        var icon = document.getElementById('scan_icon_button');
        icon.addEventListener("touchstart", touchStart, false);
        icon.addEventListener("touchmove", touchMove, false);
        icon.addEventListener("touchend", touchEnd, false);
    }

    function notrash() {
        $(".contain-item").fadeOut();
    }
    function ConfirmbBox(){
        confirm_box($("#comfirmbox"), "show", function () {
            confirm_box($("#comfirmbox"), "hide");
            vm.textpromt = "去结算";
            vm.scanQRCode();
        }, function () {
            if (ShopMenuService.buyNowShopById(vm.shopid) == null) {
                $state.go("friendlylink");
            }
            else {
                vm.sure_click();
            }
        });
    }
}